using System;
using mojoPortal.Web;
using mojoPortal.Web.Framework;
using mojoPortal.Business.WebHelpers;
using eStore.Business;
using eStore.Helpers;

namespace eStore.UI
{
    public partial class CartAdd : mojoBasePage
    {
        protected int pageId = -1;
        protected int moduleId = -1;
        protected Store store;
        protected Guid productGuid = Guid.Empty;
        protected int qtyOrdered = 1;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += Page_Load;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadSettings();
            AddToCart();
        }

        private void AddToCart()
        {
            if (productGuid == Guid.Empty) return;
            Product product = new Product(productGuid);
            //int quantity = 1;
            qtyOrdered = WebUtils.ParseInt32FromQueryString("qty", qtyOrdered);

            if (!product.IsAvailable)
            {
                WebUtils.SetupRedirect(this, Page.ResolveUrl(
                    "~/eStore/OffeDetail.aspx?pageid="
                    + pageId
                    + "&mid=" + moduleId
                    + "&Product=" + productGuid));

                return;
            }


            if ((product.Guid != productGuid) || (product.StoreGuid != store.Guid) || (store.Guid == Guid.Empty))
                return;
            //Cart cart = StoreHelper.GetCart(store.Guid);
            Cart cart = StoreHelper.GetCart();

            if (cart == null) return;
            if (!cart.AddProductToCart(product, qtyOrdered)) return;
            // redirect to cart page
            WebUtils.SetupRedirect(this,
                                   SiteRoot + "/eStore/Cart.aspx?pageid="
                                   + pageId
                                   + "&mid=" + moduleId
                                   + "&cart=" + cart.CartGuid);

            return;
        }

        private void LoadSettings()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", moduleId);

            if (moduleId == -1) { return; }

            siteSettings = CacheHelper.GetCurrentSiteSettings();

            if (CurrentPage.ContainsModule(moduleId))
            {
                //store = StoreHelper.GetStore(siteSettings.SiteGuid, ModuleID);
                store = StoreHelper.GetStore();

            }


            productGuid = WebUtils.ParseGuidFromQueryString("product", productGuid);
        }

    }
}
